import React from 'react';
import { Layout, Menu, Icon, Modal, message } from 'antd';
import MenuList from '../../utils/Sider'
import ChangeSystemModal from '../../privateModules/ms-react-changeSystemModal'
// import ChangeSystemModal from '../index'
import { treeDataFormat } from '../../utils/TreeUtil'
// import {Link, withRouter} from 'react-router-dom'
import {Link, withRouter} from 'react-router-dom'
import loginApi from '../../api/login'
import headerImg from '../../assets/img/menu-header.png'
import headerReduceImg from '../../assets/img/logo_little.png'
import commonFuc from '../../utils/commonFuc'
import api from '../../api/user'
import { postData } from '../../api/index'

import './index.scss'

const { Sider } = Layout;
const SubMenu = Menu.SubMenu;


class SiderComponent extends React.Component {
  constructor(props){
    super(props);
    // this.handleClick = this.handleClick.bind(this);
  }
  state = {
    originOrgType: 0,//0-自营旧机构；1-新机构
    theme: 'dark',
    MenuList:[],
    selectedKeys: "",
    openKeys:[''],
    sysInfo:{},//系统信息
    systemName:'',//系统名称
  }

  componentWillMount(){
    console.log(this.props)
    //获取系统信息
    api.getSysInfo({},(res)=>{
        if(res){
            this.setState({
                sysInfo:res
            })
        }
    })
    // 设置系统名称
    api.getModules({},(res)=>{
        let modules = res
        let arr = modules.filter((v)=>{return v.code=='market'})
        let systemName = ''
        let userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
        let originOrgType = 0
        if(userInfo){
          originOrgType = userInfo.originOrgType
        }
        if(arr.length>0){
            if (originOrgType) {
              systemName = arr[0].systemName || ''
            } else {
              systemName = arr[0].name || ''
            }
        }
        document.title = systemName
        this.setState({
            systemName:systemName,
            originOrgType:originOrgType
        })
    })
    // 获取菜单
    loginApi.getMenuList({code: "market"},(data)=>{ 
      if(data && data.length > 0){
        const MenuList = treeDataFormat(data,'no','pno');
        console.log(JSON.stringify(MenuList));
        
        let openKeys = [""];
        MenuList.forEach(item => {
          if(window.location.href.indexOf(item.url) > -1){
            openKeys = [item.url];
          }       
        });

        let selectedKeys = commonFuc.sessionStorage.getItem('selectedKeys')?commonFuc.sessionStorage.getItem('selectedKeys'):MenuList[0].subs[0].url;//匹配页面链接与菜单对应的url
        this.setState({
          MenuList,
          selectedKeys:selectedKeys,
          openKeys:openKeys?openKeys:[MenuList[0].url],
        })
        //如果有菜单权限且路由和selectedKeys一样，则强行跳转到selectedKeys的页面
        if(!(window.location.href.indexOf(selectedKeys) < 0 && window.location.href.indexOf('notFound') < 0)){
          this.props.history.push(selectedKeys);          
        }  
          
      }else{
        //如果没有返回菜单，则跳转到404页面
        this.props.history.push('/notFound');
      }
    })
  }


  handleClick = (e) => {
    console.log(e)
    commonFuc.sessionStorage.setItem('selectedKeys',e.key);
    this.setState({
      selectedKeys: e.key,
    });
  }
  onTitleClick = (e)=>{
      let arr = JSON.parse(JSON.stringify(this.state.openKeys))
      if(arr.indexOf(e.key)<0){//未展开就添加，已展开就删除
          arr.push(e.key)
      }else{
          arr.splice(arr.indexOf(e.key),1)
      }
      this.setState({
        openKeys:arr
      })
  }

  componentWillUpdate(a,b){
    console.log(a,b)
  }

  render() {        
    const { openKeys, selectedKeys, theme, MenuList } = this.state;
    return (      
        <Sider
          trigger={null}
          collapsible
          collapsed={this.props.collapsed}
          className={this.props.collapsed?"":'mySider'}
        >
          <div className="layout-logo">
            {/* 切换系统 */}
            {this.state.originOrgType?<ChangeSystemModal Modal={Modal} message={message} postData={postData} postDomainName={`${process.env.Text[3]}/center`}></ChangeSystemModal>:''}
              <img className="layout-logo-img" src={this.state.sysInfo.logo} />
              <div className="layout-logo-text">
                  <span className="layout-logo-sys">{this.state.systemName}</span>
                  <span className="layout-logo-company">{this.state.sysInfo.shortName}</span>
              </div>
          </div>
          <Menu
            theme={theme}
            onSelect={this.handleClick}
            openKeys={this.props.collapsed?[]:openKeys}
            selectedKeys={[selectedKeys]}
            mode="inline"
          >
            {MenuList.map((item) =>{
                return (
                  <Menu.SubMenu key={item.url} title={<span><Icon type={ item.iconType} /><span>{item.title}</span></span>} onTitleClick={this.onTitleClick}>
                    {item.subs.map((subItem) => {
                      return (
                        <Menu.Item key={subItem.url} path={subItem.url}>                        
                          <Link to={subItem.url}>
                          <span className="nav-text">{subItem.title}</span>
                          </Link>
                        </Menu.Item>
                      )
                    })}
                  </Menu.SubMenu>
                ) 
            })}          
          </Menu>
        </Sider>
    );
  }
}

export default withRouter(SiderComponent);